<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class controller_user extends lib_controller //没有定义初始化方法，这样就默认调用父类初始化方法完成几个工具类的实例化
{
	public function init($action)//各个操作之前触发，进行初始化操作,在此判断控制器动作执行权限
	{
		$operations = lib_toolkit::getOperations();
		if($action == 'addUserPage' || $action == 'doAddUser')
		{
			if(!in_array('doAddUser',$operations))
			{
				die("Permission denied.");
			}
		}
		elseif($action == 'doUserList' || $action == 'doDeleteUser' || $action == 'editUserPage' || $action == 'doUpdateUser')
		{
			if(!in_array('doUserList',$operations))//doUserList操作包括修改和删除用户(不活动)信息
			{
				die("Permission denied.");
			}
			
			if($action == 'doDeleteUser')//删除操作授权后判断只有admin和master可以删除用户
			{
				$curr_role = $this->_session_->getSession('u_role');
				if(!($curr_role == 'admin' || $curr_role == 'master'))
				{
					$flag = preg_match('/^admin,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,admin,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,admin$/',$curr_role);
					if($flag == 0) $flag = preg_match('/^master,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,master,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,master$/',$curr_role);
					
					if($flag == 0) die("Permission denied.");
				}
			}
			
			if($action == 'editUserPage')
			{
				$_session_ = $this->_session_;
				$u_id = $_session_->getSession('u_id');
				$curr_role = $_session_->getSession('u_role');
				if(!($curr_role == 'admin' || $curr_role == 'master'))
				{
					$flag = preg_match('/^admin,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,admin,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,admin$/',$curr_role);
					if($flag == 0) $flag = preg_match('/^master,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,master,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,master$/',$curr_role);
					
					
					//不是admin或master角色的用户不能展现其他用户信息的编辑页面
					if(($_REQUEST['u_id'] != $u_id) && ($flag == 0))
					{
						die("Permission denied.");
					}
				}
			}
			
			if($action == 'doUpdateUser')
			{
				$_session_ = $this->_session_;
				$curr_role = $_session_->getSession('u_role');
				if(!($curr_role == 'admin' || $curr_role == 'master'))
				{
					$flag = preg_match('/^admin,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,admin,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,admin$/',$curr_role);
					if($flag == 0) $flag = preg_match('/^master,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,master,/',$curr_role);
					if($flag == 0) $flag = preg_match('/,master$/',$curr_role);
					
					if($flag == 0)
					{
						$u_id = $_session_->getSession('u_id');
						if($_POST['u_id'] != $u_id)
						{
							die("Permission denied.");//非admin或master用户不能修改其他用户
						}
					}
				}
			}
		}
		
		lib_toolkit::filterBrowserScript();//对用户提交数据进行安全性过滤
	}
	
	public function addUserPage()
	{
		$roles = array();
//		$_mysql_ = lib_database::init();
		$_mysql_ = $this->_mysql_;
		$result = $_mysql_->findAll('rights',false,array('r_role','r_alias'));
		
		foreach($result as $v)
		{
			$roles[] = $v['r_role'];
			$roles_alias[] = $v['r_alias'];	
		}
		
		$this->assign('next_controller', 'user');
		$this->assign('next_action', 'doAddUser');
		$this->assign('roles', $roles);
		$this->assign('roles_alias', $roles_alias);
	}
	
	public function doAddUser()
	{
		$this->_layout = 'response';//ajax反馈信息不需要加载header.php和footer.php,所以不用默认的init
		$res_arr = array();
		$res_str = '';
		
		$_mysql_ = $this->_mysql_;//在父类初始化函数中被赋值
		$_xml_ = $this->_xml_;
		$prefix = $_xml_->getConfig('data/prefix');
		
		$_session_ = $this->_session_;
		$u_name = $_session_->getSession('u_name');
		
		$current_time = time();
		$ip = $_SERVER['REMOTE_ADDR'];
		$password = sha1($_POST['password']);
		
		if(empty($_POST['name']) || empty($_POST['password']) || empty($_POST['password_again']))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Submitting data is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		else
		{
			if(!(strpos($_POST['name'],'_') === false))
			{
				$res_arr = array('result' => 'error','errmsg' => '"_" is an unlegal character.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
			
			if($_POST['password'] != $_POST['password_again'])
			{
				$res_arr = array('result' => 'error','errmsg' => 'Two passwords are not equal.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
			else
			{
				$role_arr = $_mysql_->find('rights',"r_alias = '{$_POST['role_alias']}'");
				$tmp_role = $role_arr['r_role'];
				
				$result = $_mysql_->findAll('users');
				
				foreach($result as $v)
				{
					if($v['u_name'] == $_POST['name'])
					{
						if($v['u_active'] == '1')//已经有活动用户了
						{
							$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('add user',$current_time,'$ip','add user {$_POST['name']} error,System have this user.','{$u_name}')");
							$res_arr = array('result' => 'error','errmsg' => 'The user has existed.');
							$res_str = json_encode($res_arr);
							$this->assign('res_str', $res_str);
							return 'result';
						}
						elseif($v['u_active'] == '0')//添加的用户不活动，则修改此用户为活动
						{
							$_mysql_->customSql("DELETE FROM {$prefix}users WHERE u_id = {$v['u_id']}");
							$_mysql_->customSql("INSERT INTO {$prefix}users (u_id,u_name,u_role,u_password,u_active,u_cellphone,u_email) VALUES ({$v['u_id']},'{$_POST['name']}','unassign','$password',1,'{$_POST['cellphone']}','{$_POST['email']}')");
							$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('add user',$current_time,'$ip','Active this user:{$_POST['name']}','{$u_name}')");
							$res_arr = array('result' => 'ok','sucmsg' => 'Add user successfully.');
							$res_str = json_encode($res_arr);
							$this->assign('res_str', $res_str);
							return 'result';
						}
					}
				}
				
				$_mysql_->customSql("INSERT INTO {$prefix}users (u_name,u_role,u_password,u_active,u_cellphone,u_email) VALUES ('{$_POST['name']}','unassign','$password',1,'{$_POST['cellphone']}','{$_POST['email']}')");
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('add user',$current_time,'$ip','add user:{$_POST['name']}','{$u_name}')");
				$res_arr = array('result' => 'ok','sucmsg' => 'Add user successfully.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
		}
	}
	
	public function doUserList()
	{
		$_mysql_ = $this->_mysql_;
		$_session_= $this->_session_;
		
		$u_role = $_session_->getSession('u_role');
		$u_id = $_session_->getSession('u_id');
		
		if($u_role == 'admin' || $u_role == 'master')
		{
			$res_arr = $_mysql_->findAll('users',"u_active = 1 ORDER BY u_role ASC");
			$flag_showAll = true;
		}
		else
		{
			$curr_role = $u_role;
			$flag = preg_match('/^admin,/',$curr_role);
			if($flag == 0) $flag = preg_match('/,admin,/',$curr_role);
			if($flag == 0) $flag = preg_match('/,admin$/',$curr_role);
			if($flag == 0) $flag = preg_match('/^master,/',$curr_role);
			if($flag == 0) $flag = preg_match('/,master,/',$curr_role);
			if($flag == 0) $flag = preg_match('/,master$/',$curr_role);
			
			if($flag == 0)
			{
				$res_arr = $_mysql_->find('users',"u_id = $u_id AND u_active = 1");
				$flag_showAll = false;
			}
			elseif($flag == 1)
			{
				$res_arr = $_mysql_->findAll('users',"u_active = 1 ORDER BY u_role ASC");
				$flag_showAll = true;
			}
		}
		
		if(empty($res_arr))
		{
			die("Permission denied.");
		}
		
		$rights_arr = $_mysql_->findAll('rights');
		$rights = array();
		foreach($rights_arr as $v)
		{
			$tmp = $v['r_role'];
			$rights[$tmp] = $v['r_alias'];
		}
		
		$this->assign('res_arr', $res_arr);
		$this->assign('rights', $rights);
		$this->assign('flag_showAll', $flag_showAll);
	}
	
	public function doDeleteUser()
	{
		$this->_layout = 'response';
		
		$_session_ = $this->_session_;
		$_mysql_ = $this->_mysql_;
		$u_id = intval($_GET['id']);
		if(empty($u_id))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		else
		{
			$users = $_mysql_->find('users',"u_id = $u_id");
			if(empty($users))
			{
				$res_arr = array('result' => 'error','errmsg' => 'This user can not exist.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
			else
			{
				if($users['u_name'] == 'admin')
				{
					$res_arr = array('result' => 'error','errmsg' => 'Admin can not be deleted.');
					$res_str = json_encode($res_arr);
					$this->assign('res_str', $res_str);
					return 'result';
				}
				$current_time = time();
				$ip = $_SERVER['REMOTE_ADDR'];
				$operator = $_session_->getSession('u_name');
				
				$_xml_ = $this->_xml_;
				$prefix = $_xml_->getConfig('data/prefix');
				
				$_mysql_->customSql("UPDATE {$prefix}users SET u_active = 0 WHERE u_id = $u_id");
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('Inactive user',$current_time,'$ip','Inactive user: {$users['u_name']}.','$operator')");
								
				$res_arr = array('result' => 'ok','sucmsg' => 'Delete user successfully.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
		}
	}
	
	public function editUserPage()
	{
		$u_id = intval($_GET['u_id']);
		$isExist = (empty($u_id)) ? true : false;
		
		if(!$isExist)
		{
			$_mysql_ = $this->_mysql_;
			$user_info = $_mysql_->find('users',"u_id = $u_id");
			$isExist = empty($user_info) ? true : false;
		}
		
		$this->assign('isExist',$isExist);
		$this->assign('user_info', $user_info);
		$this->assign('next_controller', 'user');
		$this->assign('next_action','doUpdateUser');
	}
	
	public function doUpdateUser()
	{
		$this->_layout = 'response';
		
		$ip = $_SERVER['REMOTE_ADDR'];
		$current_time = time();
		
		$_session_ = $this->_session_;
		$operator = $_session_->getSession('u_name'); 
		
		$_xml_ = $this->_xml_;
		$prefix = $_xml_->getConfig('data/prefix');
		
		$name = $_POST['name'];
		$password = trim($_POST['password']);
		$password_again = trim($_POST['password_again']);
		$email = trim($_POST['email']);
		$cellphone = trim($_POST['cellphone']);
		$u_id = $_POST['u_id'];
		
		if(empty($name))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Name is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		
		if($name == 'admin')
		{
			$res_arr = array('result' => 'error','errmsg' => 'Admin can not be edited.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		
		if(!(strpos($name,'_') === false))
		{
			$res_arr = array('result' => 'error','errmsg' => '"_" is an unlegal character.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		
//		if(!empty($password) || !empty($password_again))
//		{
			if($password != $password_again)
			{
				$res_arr = array('result' => 'error','errmsg' => 'Two passwords are not equal.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
			else
			{
				$_mysql_ = $this->_mysql_;
				
				$others = $_mysql_->findAll("users","u_id <> $u_id");
				foreach($others as $v)
				{
					if($v['u_name'] == $name)//修改用户名时不能改成已有用户的名字
					{
						$res_arr = array('result' => 'error','errmsg' => 'This user has existed,or this user has existed in a period of time.');
						$res_str = json_encode($res_arr);
						$this->assign('res_str', $res_str);
						return 'result';
					}
				}
				
				
				if(empty($password) && empty($password_again))
				{
					$_mysql_->customSql("UPDATE {$prefix}users SET u_name = '$name',u_email = '$email',u_cellphone = '$cellphone' WHERE u_id = $u_id");
				}
				else
				{
					$password = sha1($password);
					$_mysql_->customSql("UPDATE {$prefix}users SET u_name = '$name',u_password = '$password',u_email = '$email',u_cellphone = '$cellphone' WHERE u_id = $u_id");
				}
				
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('Update user',$current_time,'$ip','Update user: $name.','$operator')");
				$res_arr = array('result' => 'ok','sucmsg' => 'Update users successfully.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
//		}
//		else
//		{
//			$res_arr = array('result' => 'error','errmsg' => 'Password is empty.');
//			$res_str = json_encode($res_arr);
//			$this->assign('res_str', $res_str);
//			return 'result';
//		}
	}
}
?>